package org.smoke.controllers;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Post;
import org.json.JSONObject;
import org.smoke.bean.User;
import org.smoke.bean.UserToken;
import org.smoke.bean.enumerate.ApiStatus;
import org.smoke.constants.ServerConstants;
import org.smoke.service.UserService;
import org.smoke.validator.annotation.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;

import static org.smoke.constants.ServerConstants.*;


/**
 * @author hezhiyu on 14/10/30.
 */
@Path("user")
@Component
public class UserController {

    @Autowired
    private UserService userService;

    @Post("login")
    public String login(Invocation inv,
                        @NotBlank @Param(USER_NAME) String name,
                        @NotBlank @Param(USER_PASS) String pass) {

        Long uid = userService.login(name, pass);
        if (uid == null) {
            return PREFIX + ApiStatus.USER_NOT_EXIST;
        }
        String userToken = userService.buildUserToken(uid, inv.getRequest().getRemoteAddr());
        if (userToken == null) {
            return PREFIX + ApiStatus.SERVER_ERROR;
        }
        Cookie cookie = new Cookie(ServerConstants.COOKIE_NAME, userToken);
        cookie.setMaxAge(3600 * 24 * 30);
        cookie.setPath("/");
        inv.getResponse().addCookie(cookie);
        JSONObject res = new JSONObject();
        res.put("token", userToken);
        res.put("uid", uid);
        return PREFIX + ApiStatus.SUCCESS.wrapper(res);
    }

    @Post("register")
    public String register(@NotBlank @Param(USER_PASS) String pass,
                           @NotBlank @Param(USER_NAME) String name) {
        boolean userExist = userService.checkUserExist(name);
        if (userExist) {
            return PREFIX + ApiStatus.USER_EXIST;
        }
        User user = userService.registerUser(name, pass);
        if (user == null) return PREFIX + ApiStatus.SERVER_ERROR;
        JSONObject res = new JSONObject();
        res.put("uid", user.getUid());
        return PREFIX + ApiStatus.SUCCESS.wrapper(res);
    }

    @Post("logout")
    public String logout(Invocation inv,
                         @Param(USER_TOKEN) UserToken token) {
        long uid = token.getUid();
        if (uid < 0) {
            return PREFIX + ApiStatus.TOKEN_ERROR;
        }
        Cookie cookie = new Cookie(ServerConstants.COOKIE_NAME, "");
        cookie.setMaxAge(0);
        cookie.setPath("/");
        inv.getResponse().addCookie(cookie);
        return PREFIX + ApiStatus.SUCCESS;
    }
}
